/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package multichatserver;

import java.nio.*;
import java.nio.channels.*;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.w3c.dom.*;

class ChatServer extends Thread {


    static final int PORT = 1234;  // port for this server
    ArrayList<Client> clients;
    ServerSocket serverSock;
    InetAddress serverAddress;
    int id = 0;

    DatagramChannel udpChannel;

    public ChatServer() {
        try {
            udpChannel = DatagramChannel.open();
            udpChannel.socket().bind(new InetSocketAddress(PORT));
        } catch (IOException ex) {
            System.out.println("chyba pri vytvareni udp datagram channelu");
        }

        try {
            serverSock = new ServerSocket(PORT);
            System.out.println("Server created at address" + serverSock.getInetAddress());
        } catch (Exception e) {
            System.out.println("Creating server ERROR");
            e.printStackTrace();
        }

        try {
            clients = new ArrayList<Client>();
            Socket clientSock;
            while (true) {
                System.out.println("Waiting for a client...");
                clientSock = serverSock.accept();
                clients.add(new Client(id,clientSock));
                id++;
                new ChatServerHandler(clients.get(clients.size()-1), clients).start();
            }
        } catch (Exception e) {
            System.out.println("Accepting client ERROR");
            e.printStackTrace();
        }
    }

    /**
     * Uzavre spojeni
     */
    public void konec() {
        try {
            serverSock.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}